<template>
	<view class="">
		<!-- 顶部导航 -->
		<fa-navbar title="发布文章"></fa-navbar>
		<view class="u-p-30">
			<u-form :model="form" :rules="rules" ref="uForm">
				<u-form-item :label-position="labelPosition" label="文章分类：" prop="category_name" label-width="150">
					<u-input
						:border="border"
						type="select"
						:select-open="selectShow"
						v-model="form.category_name"
						placeholder="请选择文章分类"
						@click="selectShow = true"
					></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="文章标题：" label-width="150" prop="title">
					<u-input v-model="form.title" placeholder="请输入文章标题" />
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="文章标签：" label-width="150" prop="tags">
					<view class="" style="width: 100%;">
						<view class="u-flex u-row-between">
							<view class="">
								<u-tag
									:bg-color="theme.lightColor"
									:border-color="theme.faBorderColor"
									:color="theme.bgColor"
									:text="item"
									class="u-m-r-10"
									v-for="(item, index) in tags"
									:key="index"
									mode="light"
									:closeable="true"
									@close="closeTag(index)"
								/>
							</view>
							<view class="u-m-l-10"><u-button hover-class="none" type="error" size="mini" @click="addTags(0)">清空标签</u-button></view>
						</view>
						<u-input placeholder="请输入文章标签" :clearable="false" :border="border" type="select" :select-open="tagsShow" @click="tagsShow = true"/>
					</view>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="所属专区(可选)：" prop="zone_name" label-width="150">
					<u-input
						:border="border"
						type="select"
						:select-open="zoneShow"
						v-model="form.zone_name"
						placeholder="请选择所属专区"
						@click="zoneShow = true"
					></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="文章摘要(可选)：" prop="summary" label-width="150">
					<u-input :border="border" type="textarea" v-model="form.summary"></u-input>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="文章内容：" prop="content" label-width="150">
					<!-- #ifdef MP-WEIXIN || APP-PLUS || H5 -->
					<view class="" v-if="is_show || type != 'update'"><fa-editor ref="faEditor" :html="content_fmt"></fa-editor></view>
					<!-- #endif -->
					<!-- #ifdef MP-BAIDU || MP-ALIPAY -->
					<fa-markdown ref="faEditor"></fa-markdown>
					<!-- #endif -->
				</u-form-item>

				<view class="u-border-bottom" v-if="this.vuex_config.awardtype != 'none'">
					<u-form-item :label-position="labelPosition" prop="radio" label-width="150">
						<view class="u-flex">
							<view class="u-flex-1">
								<u-radio-group v-model="switpricetype">
									<u-radio :active-color="theme.bgColor" v-for="(item, index) in radioList" :key="index" :name="item.pricetype">
										{{ item.name }}
									</u-radio>
								</u-radio-group>
							</view>
							<view class="" @click="tipsClick">
								<u-icon name="question-circle-fill"></u-icon>
								<text>付费规则</text>
							</view>
						</view>
					</u-form-item>
					<u-grid :col="2" :border="false">
						<u-grid-item>
							<view class="fa-grid">
								<u-button
									hover-class="none"
									throttle-time="0"
									type="primary"
									:custom-style="{
										backgroundColor: btnBgColor(money == 0),
										color: btnColor(money == 0),
										border: '1px solid ' + theme.faBorderColor
									}"
									@click="selectPrice(0)"
								>
									无
								</u-button>
							</view>
						</u-grid-item>
						<u-grid-item v-for="(item, index) in pricelist" :key="index">
							<view class="fa-grid">
								<u-button
									hover-class="none"
									throttle-time="0"
									type="primary"
									:custom-style="{
										backgroundColor: btnBgColor(item.check),
										color: btnColor(item.check),
										border: '1px solid ' + theme.faBorderColor
									}"
									v-text="item.key"
									@click="selectPrice(item.value, index)"
								></u-button>
							</view>
						</u-grid-item>
						<u-grid-item
							v-if="(vuex_config.iscustomprice == '1' && switpricetype == 'price') || (vuex_config.iscustomscore == '1' && switpricetype == 'score')"
						>
							<view class="fa-grid">
								<input
									@focus="inputInput"
									@blur="inputInput"
									@input="inputInput"
									:value="custom_money"
									type="text"
									:style="[
										{
											color: theme.bgColor,
											border: '1px solid' + theme.bgColor
										}
									]"
									class="custom"
								/>
							</view>
						</u-grid-item>
					</u-grid>
				</view>
				<fa-captchaparts ref="addcapt" mode="postarticle" v-model="form.captcha"></fa-captchaparts>
			</u-form>
			<view class="u-p-30">
				<u-button hover-class="none" type="primary" :custom-style="{ backgroundColor: theme.bgColor, color: theme.color }" @click="submit">
					提交文章
				</u-button>
			</view>
			<!-- 顶部提示 -->
			<fa-u-top-tips ref="uTips" :is-html="true" type="" :bg-color="theme.bgColor" :navbar-height="statusBarHeight + navbarHeight"></fa-u-top-tips>
			<!-- 分类选择 -->
			<u-select
				mode="single-column"
				:confirm-color="theme.bgColor"
				:list="categoryList"
				v-model="selectShow"
				value-name="id"
				label-name="name"
				@confirm="selectConfirm"
			></u-select>
			<!-- 问题标签选择 -->
			<u-select
				mode="single-column"
				:confirm-color="theme.bgColor"
				:list="tagsList"
				v-model="tagsShow"
				value-name="id"
				label-name="name"
				@confirm="tagsConfirm"
			></u-select>
			<!-- 专区选择 -->
			<u-select
				mode="single-column"
				:confirm-color="theme.bgColor"
				:list="zoneList"
				v-model="zoneShow"
				value-name="id"
				label-name="name"
				@confirm="zoneConfirm"
			></u-select>
			<!-- 底部导航 -->
			<fa-tabbar></fa-tabbar>
		</view>
	</view>
</template>

<script>
export default {
	computed: {
		awardtype() {
			if (!this.vuex_config.awardtype) {
				return '';
			}
			return this.vuex_config.awardtype;
		}
	},
	onLoad(e) {
		let query = this.$Route.query || e || {};
		this.tag_id = query.tag_id || 0;
		this.zone_id = query.zone_id || 0;
		//如果是更新文章的话
		this.type = query.type || '';
		if (this.type == 'update') {
			this.id = query.id || 0;
			uni.setNavigationBarTitle({
				title: '更新文章'
			});
			this.getArticleUpdate();
			return;
		}
		if (!this.vuex_token) {
			this.getArticlePost();
			this.getTags()
		}
	},
	onShow() {
		if (this.vuex_token) {
			this.getArticlePost();
			this.getTags()
		}
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	watch: {
		awardtype: {
			handler: function(newValue, oldValue) {
				if (!newValue) return;
				//根据后台配置设定
				this.switpricetype = 'price';
				if (newValue == 'score') {
					this.radioList.splice(0, 1);
					this.switpricetype = 'score';
				} else if (newValue == 'money') {
					this.radioList.splice(1, 1);
				}
			},
			immediate: true
		},
		switpricetype: {
			handler: function(newValue, oldValue) {
				this.form.switpricetype = newValue;
				let list = newValue == 'price' ? this.vuex_config.pricelist : this.vuex_config.scorelist;
				this.pricelist = [];
				for (let i in list) {
					this.pricelist.push({
						key: i,
						value: list[i],
						check: false
					});
				}
			},
			immediate: true
		},
		tags: {
			handler: function(newValue, oldValue) {
				this.form.tags = newValue.join(',');
			},
			deep: true,
			immediate: true
		},
		money(newValue, oldValue) {
			if (this.switpricetype == 'price') {
				this.form.price = newValue;
				this.form.score = 0;
			} else {
				this.form.price = 0;
				this.form.score = newValue;
			}
			let index = -1;
			this.pricelist.forEach((item, i) => {
				item.check = false;
				if (newValue == item.value) {
					index = i;
				}
			});
			if (index != -1) {
				this.$set(this.pricelist[index], 'check', true);
			}
		}
	},
	data() {
		return {
			// 状态栏高度，H5中，此值为0，因为H5不可操作状态栏
			statusBarHeight: uni.getWindowInfo().statusBarHeight,
			// 导航栏内容区域高度，不包括状态栏高度在内
			navbarHeight: 44,
			tag_id: 0,
			type: '',
			zone_id: 0,
			labelPosition: 'top',
			border: false,
			content_fmt: '',
			is_show: false,
			form: {
				title: '',
				summary: '',
				tags: '',
				category_id: '',
				category_name: '',
				zone_name: '',
				zone_id: '',
				content: '',
				switpricetype: 'price',
				price: 0,
				score: 0,
				captcha:''
			},
			rules: {
				category_name: [
					{
						required: true,
						message: '请选择文章分类',
						trigger: ['change', 'blur']
					}
				],
				title: [
					{
						required: true,
						message: '请输入文章标题',
						trigger: ['change', 'blur']
					},
					{
						min: 5,
						message: '文章标题至少为5个字符',
						trigger: ['change', 'blur']
					}
				],
				tags: [
					{
						required: true,
						message: '请添加标签',
						trigger: ['change', 'blur']
					}
				]
			},
			radioList: [
				{
					name: '付费金额',
					pricetype: 'price'
				},
				{
					name: '付费积分',
					pricetype: 'score'
				}
			],
			categoryList: [],
			zoneList: [],
			custom_money: '自定义',
			money: '',
			switpricetype: '',
			pricelist: [],
			lsTag: '',
			tags: [],
			selectShow: false,
			zoneShow: false,
			errorType: ['message'],
			user: {},
			tagsList:[],
			tagsShow: false,
		};
	},
	methods: {
		//添加文章，获取信息
		getArticlePost: async function() {
			let res = await this.$api.getArticlePost({
				tag_id: this.tag_id,
				zone_id: this.zone_id
			});
			if (!res.code) {
				this.$u.toast(res.msg);
				return;
			}
			this.categoryList = res.data.categoryList;
			this.user = res.data.user || {};
			let zlist = [{ id: 0, name: '不关联专区' }];
			zlist = zlist.concat(res.data.zoneList);
			this.zoneList = zlist;
			if (res.data.tag) {
				this.tags.push(res.data.tag.name);
			}
			if (res.data.zone && res.data.zone.id) {
				this.form.zone_id = res.data.zone.id;
				this.form.zone_name = res.data.zone.name;
			}
		},
		//更新文章，获取信息
		getArticleUpdate: async function() {
			let res = await this.$api.getArticleUpdate({
				id: this.id
			});
			if (!res.code) {
				this.$u.toast(res.msg);
				return;
			}
			this.categoryList = res.data.categoryList;
			this.user = res.data.user || {};
			//为表单赋值
			this.form.category_id = res.data.article.category_id;
			this.form.title = res.data.article.title;
			this.form.tags = res.data.article.tags_text;
			this.form.summary = res.data.article.summary;
			this.tags = res.data.article.tags_text.split(',');
			this.content_fmt = res.data.article.content_fmt;
			console.log(this.content_fmt);
			// #ifdef MP-BAIDU || MP-ALIPAY
			this.$refs.faEditor.setData(res.data.article.content_fmt);
			// #endif
			this.is_show = true;
			res.data.categoryList.forEach(item => {
				if (item.id == res.data.article.category_id) {
					this.form.category_name = item.name;
				}
			});
		},
		
		async getTags() {
			let res = await this.$api.getQuestionTags();
			if (!res.code) {
				this.$u.toast(res.msg);
				return;
			}
			let data = res.data;
			let temp = []
			for (let item in data) {
				temp.push({
					id:item,
					name:data[item],
					type: 'tags',
				})
			}
			this.tagsList = temp
		},
		//添加标签或清空标签
		addTags(type) {
			if (!type) {
				this.tags = [];
				return;
			}
			if (this.tags.indexOf(this.lsTag) != -1) {
				this.$u.toast('标签内容重复');
				return;
			}
			if (this.tags.length >= 3) {
				this.$u.toast('标签最多可添加3个哦');
				return;
			}
			this.tags.push(this.lsTag);
			this.lsTag = '';
		},
		//移除标签
		closeTag(index) {
			this.tags.splice(index, 1);
		},
		zoneConfirm(e) {
			e.map((val, index) => {
				this.form.zone_name = val.label;
				this.form.zone_id = val.value;
			});
		},
		//显示提示
		tipsClick() {
			let title = `温馨提示<br>
					1、用户需要支付设定的费用后才可以查看付费内容<br>
					2、平台会统一扣除30%的技术服务费<br>
					3、收入明细可以在会员中心->余额日志中查看<br>
					4、只有认证专家可以发布付费阅读文章`;
			this.$refs.uTips.show({
				title: title,
				type: 'warning',
				duration: '5000'
			});
		},
		// 选择回调
		selectConfirm(e) {
			e.map((val, index) => {
				this.form.category_id = val.value;
				this.form.category_name = val.label;
			});
		},
		tagsConfirm(e) {
			e.map((val, index) => {
				this.lsTag = val.label
				this.addTags(1)
			});
		},
		//选择积分或金额
		selectPrice(value, index) {
			this.money = value;
			this.custom_money = '自定义';
		},
		//自定义或积分
		inputInput(e) {
			if (e.type == 'blur') {
				this.custom_money = !e.detail.value ? '自定义' : e.detail.value;
				return;
			}
			if (e.type == 'focus') {
				this.custom_money = e.detail.value == '自定义' ? '' : e.detail.value;
				return;
			}
			this.money = e.detail.value;
			this.custom_money = e.detail.value;
		},
		//添加数据
		async submit() {
			this.form.content = await this.$refs.faEditor.getData();
			if (!this.form.content) {
				this.$u.toast('请输入文章内容！');
				return;
			}
			this.$refs.uForm.validate(async valid => {
				if (valid) {
					let res = {};
					if (!this.id) {
						res = await this.$api.goArticlePost(this.form);
						this.$u.toast(res.msg);
						if (!res.code) {
							this.$refs.addcapt.getCaptcha()
							return;
						}
						this.$Router.replace({ path: '/pages/community/article/detail', query: { id: res.data } });
					} else {
						this.form.id = this.id;
						res = await this.$api.goArticleUpdate(this.form);
						this.$u.toast(res.msg);
						if (!res.code) {	
							this.$refs.addcapt.getCaptcha()
							return;
						}
						let pages = getCurrentPages();
						setTimeout(() => {
							if (pages.length == 1) {
								//只有当前页面了
								this.$wanlshop.to('/pages/community/article/index');
							} else {
								this.$Router.back(1);
							}
						}, 800);
					}
				} else {
					this.$u.toast('验证失败');
				}
			});
		}
	}
};
</script>

<style>
page {
	background-color: #ffffff;
}
.fa-grid {
	width: 100%;
	padding: 0 20rpx;
}
.custom {
	text-align: center;
	background-color: rgb(255, 255, 255);
	height: 80rpx;
	border-radius: 10rpx;
	font-size: 30rpx;
}
</style>
